<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色菜单权限管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .menu-tree {
            margin-top: 20px;
        }
        
        .menu-item {
            padding: 10px;
            border: 1px solid #dcdfe6;
            margin-bottom: 5px;
            border-radius: 4px;
        }
        
        .menu-item.children {
            background-color: #f8f9fa;
        }
        
        .menu-header {
            display: flex;
            align-items: center;
        }
        
        .menu-checkbox {
            margin-right: 10px;
        }
        
        .menu-info {
            flex: 1;
        }
        
        .menu-name {
            font-weight: bold;
        }
        
        .menu-path {
            color: #909399;
            font-size: 12px;
            margin-left: 10px;
        }
        
        .submenu {
            margin-left: 30px;
            margin-top: 5px;
        }
        
        .actions {
            margin-top: 20px;
            text-align: center;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error {
            color: #f56c6c;
            padding: 10px;
            background-color: #fef0f0;
            border: 1px solid #fde2e2;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .success {
            color: #67c23a;
            padding: 10px;
            background-color: #f0f9ec;
            border: 1px solid #e1f3d8;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>角色菜单权限管理 <span id="roleName"></span></h2>
            <button class="btn btn-default" onclick="history.back()">返回</button>
        </div>
        
        <div id="message" class="hidden"></div>
        
        <div class="card">
            <h3>菜单权限</h3>
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            <div class="menu-tree" id="menuTree">
                <!-- 菜单树将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <div class="actions">
            <button class="btn btn-primary" onclick="savePermissions()">保存权限</button>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 当前角色名称
        const roleName = new URLSearchParams(window.location.search).get('name');
        // 所有菜单数据
        let menuData = [];
        // 角色当前拥有的菜单权限
        let rolePolicies = [];
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', async function() {
            if (!roleName) {
                alert('缺少角色名称参数');
                history.back();
                return;
            }
            
            document.getElementById('roleName').textContent = `- ${roleName}`;
            
            showLoading(true);
            await Promise.all([
                loadMenus(),
                loadRolePolicies()
            ]);
            showLoading(false);
            
            renderMenuTree();
        });
        
        // 显示消息
        function showMessage(message, type = 'info') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = message;
            messageEl.className = type;
            messageEl.classList.remove('hidden');
            
            // 3秒后自动隐藏
            setTimeout(() => {
                messageEl.classList.add('hidden');
            }, 3000);
        }
        
        // 显示错误消息
        function showError(message) {
            showMessage(message, 'error');
        }
        
        // 显示成功消息
        function showSuccess(message) {
            showMessage(message, 'success');
        }
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const menuTree = document.getElementById('menuTree');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                menuTree.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                menuTree.style.display = 'block';
            }
        }
        
        // 获取菜单数据
        async function loadMenus() {
            try {
                const response = await fetch('/menu/list', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    menuData = result.data || [];
                } else {
                    throw new Error(`获取菜单数据失败，状态码: ${response.status}`);
                }
            } catch (error) {
                console.error('获取菜单数据异常:', error);
                showError('获取菜单数据失败: ' + error.message);
                menuData = []; // 确保menuData是一个数组，即使加载失败
            }
        }
        
        // 获取角色已分配的策略
        async function loadRolePolicies() {
            try {
                const response = await fetch(`/casbin-role/${roleName}/policies`, {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    rolePolicies = result.data || [];
                } else {
                    rolePolicies = [];
                }
            } catch (error) {
                console.error('获取角色策略异常:', error);
                rolePolicies = [];
            }
        }
        
        // 渲染菜单树
        function renderMenuTree() {
            const container = document.getElementById('menuTree');
            container.innerHTML = '';
            
            function createMenuItem(menu) {
                const menuItem = document.createElement('div');
                menuItem.className = menu.children && menu.children.length > 0 ? 'menu-item children' : 'menu-item';
                
                // 检查该菜单是否已分配给角色
                const hasPermission = rolePolicies.some(policy => 
                    policy[0] === roleName && 
                    policy[1] === menu.path && 
                    policy[2] === 'read'
                );
                
                menuItem.innerHTML = `
                    <div class="menu-header">
                        <input type="checkbox" class="menu-checkbox" id="menu_${menu.id}" 
                               data-id="${menu.id}" data-path="${menu.path || ''}" ${hasPermission ? 'checked' : ''}>
                        <div class="menu-info">
                            <span class="menu-name">${menu.icon || '📁'} ${menu.name}</span>
                            ${menu.path ? `<span class="menu-path">(${menu.path})</span>` : ''}
                        </div>
                    </div>
                `;
                
                // 子菜单
                if (menu.children && menu.children.length > 0) {
                    const submenuContainer = document.createElement('div');
                    submenuContainer.className = 'submenu';
                    
                    menu.children.forEach(child => {
                        const childElement = createMenuItem(child);
                        submenuContainer.appendChild(childElement);
                    });
                    
                    menuItem.appendChild(submenuContainer);
                }
                
                return menuItem;
            }
            
            menuData.forEach(menu => {
                if (menu.parentId === 0) {  // 只渲染顶级菜单
                    const menuItem = createMenuItem(menu);
                    container.appendChild(menuItem);
                }
            });
            
            // 绑定复选框事件
            document.querySelectorAll('.menu-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const menuId = this.dataset.id;
                    const menuPath = this.dataset.path;
                    
                    if (this.checked) {
                        console.log(`选中菜单: ${menuId}, 路径: ${menuPath}`);
                    } else {
                        console.log(`取消选中菜单: ${menuId}, 路径: ${menuPath}`);
                    }
                });
            });
        }
        
        // 保存权限
        async function savePermissions() {
            try {
                showLoading(true);
                
                // 先清空角色的所有权限
                const clearResponse = await fetch(`/casbin-role/${roleName}/policies/clear`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!clearResponse.ok) {
                    let errorMessage = `清空角色权限失败: ${clearResponse.status}`;
                    try {
                        const errorResult = await clearResponse.json();
                        errorMessage = errorResult.message || errorMessage;
                    } catch (e) {
                        // 如果无法解析JSON，使用默认错误消息
                    }
                    throw new Error(errorMessage);
                }
                
                // 获取所有选中的菜单
                const checkedMenus = Array.from(document.querySelectorAll('.menu-checkbox:checked'));
                
                // 为每个选中的菜单添加权限
                let successCount = 0;
                const failedPermissions = [];
                
                for (const checkbox of checkedMenus) {
                    const menuPath = checkbox.dataset.path;
                    if (menuPath) {
                        try {
                            const response = await fetch(`/casbin-role/${roleName}/policies`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ 
                                    resource: menuPath,
                                    action: 'read'
                                }),
                                credentials: 'include'
                            });
                            
                            if (response.ok) {
                                successCount++;
                            } else {
                                let errorMessage = `状态码: ${response.status}`;
                                try {
                                    const errorResult = await response.json();
                                    errorMessage = errorResult.message || errorMessage;
                                } catch (e) {
                                    // 如果无法解析JSON，使用默认错误消息
                                }
                                failedPermissions.push({
                                    path: menuPath,
                                    error: errorMessage
                                });
                            }
                        } catch (error) {
                            failedPermissions.push({
                                path: menuPath,
                                error: error.message
                            });
                        }
                    }
                }
                
                showLoading(false);
                
                // 构建消息
                let message = `权限保存完成，成功设置 ${successCount} 个菜单权限`;
                if (failedPermissions.length > 0) {
                    message += `，${failedPermissions.length} 个权限设置失败`;
                    console.error('失败的权限设置:', failedPermissions);
                }
                
                showSuccess(message);
                
                // 重新加载权限
                await loadRolePolicies();
                renderMenuTree();
                
                // 如果有失败的权限设置，在控制台显示详细信息
                if (failedPermissions.length > 0) {
                    console.warn('以下权限设置失败:', failedPermissions);
                }
            } catch (error) {
                showLoading(false);
                console.error('保存权限异常:', error);
                showError('保存权限时发生错误: ' + error.message);
            }
        }
    </script>
</body>
</html>